{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "122b1f66-45c1-4051-8dd3-e509ba64333a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "生成的提示词:\n",
      "你是一个非常有经验和天赋的程序员，现在给你如下函数名称，你会按照如下格式，输出这段代码的名称、源代码、中文解释。\n",
      "函数名称: hello_world\n",
      "源代码:\n",
      "def hello_world(abc):\n",
      "    print(\"Hello, world!\")\n",
      "    return abc\n",
      "\n",
      "代码解释:\n",
      "\n",
      "\n",
      "==================================================\n",
      "\n",
      "AI 回复:\n",
      "当然可以！以下是按照你提供的格式输出的函数信息：\n",
      "\n",
      "---\n",
      "\n",
      "**代码名称**: hello_world\n",
      "\n",
      "**源代码**:\n",
      "```python\n",
      "def hello_world(abc):\n",
      "    print(\"Hello, world!\")\n",
      "    return abc\n",
      "```\n",
      "\n",
      "**中文解释**:  \n",
      "该函数名为 `hello_world`，接受一个参数 `abc`（但该参数在函数体内并未被使用）。函数的功能是打印字符串 `\"Hello, world!\"`，然后直接返回传入的参数 `abc`。  \n",
      "这个函数结合了打印输出和返回值的功能，尽管参数和打印内容没有直接关联，但这是合法的 Python 写法。常用于演示函数的定义与基本用法。\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import inspect\n",
    "from langchain.prompts import StringPromptTemplate\n",
    "from openai import OpenAI  # 新版导入方式\n",
    "\n",
    "# 配置阿里云的 API 密钥和基础 URL\n",
    "api_key = \"sk-4e88cf4db3e14894bafaff606d296610\"\n",
    "api_base = \"https://dashscope.aliyuncs.com/compatible-mode/v1\"\n",
    "\n",
    "# 初始化 OpenAI 客户端（新版方式）\n",
    "client = OpenAI(\n",
    "    api_key=api_key,\n",
    "    base_url=api_base\n",
    ")\n",
    "\n",
    "# 定义一个简单的函数作为示例效果\n",
    "def hello_world(abc):\n",
    "    print(\"Hello, world!\")\n",
    "    return abc\n",
    "\n",
    "PROMPT = \"\"\"\\\n",
    "你是一个非常有经验和天赋的程序员，现在给你如下函数名称，你会按照如下格式，输出这段代码的名称、源代码、中文解释。\n",
    "函数名称: {function_name}\n",
    "源代码:\n",
    "{source_code}\n",
    "代码解释:\n",
    "\"\"\"\n",
    "\n",
    "def get_source_code(function_name):\n",
    "    # 获得源代码\n",
    "    return inspect.getsource(function_name)\n",
    "\n",
    "# 自定义的模板 class\n",
    "class CustomPrompt(StringPromptTemplate):\n",
    "    def format(self, **kwargs) -> str:\n",
    "        # 获得源代码\n",
    "        source_code = get_source_code(kwargs[\"function_name\"])\n",
    "\n",
    "        # 生成提示词模板\n",
    "        prompt = PROMPT.format(\n",
    "            function_name=kwargs[\"function_name\"].__name__, source_code=source_code\n",
    "        )\n",
    "        return prompt\n",
    "\n",
    "# 生成提示词\n",
    "a = CustomPrompt(input_variables=[\"function_name\"])\n",
    "pm = a.format(function_name=hello_world)\n",
    "\n",
    "print(\"生成的提示词:\")\n",
    "print(pm)\n",
    "print(\"\\n\" + \"=\"*50 + \"\\n\")\n",
    "\n",
    "# 使用新版 API 进行预测\n",
    "response = client.chat.completions.create(\n",
    "    model=\"qwen-plus\",  # 阿里云的模型名称\n",
    "    messages=[\n",
    "        {\"role\": \"user\", \"content\": pm}\n",
    "    ],\n",
    "    # 可选参数\n",
    "    temperature=0.7,\n",
    "    max_tokens=1000\n",
    ")\n",
    "\n",
    "print(\"AI 回复:\")\n",
    "print(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a1c0ab47-9ac5-4093-83bd-10ace1654253",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你是一个非常有经验和天赋的程序员，现在给你如下函数名称，你会按照如下格式，输出这段代码的名称、源代码、中文解释。\n",
      "函数名称: hello_world\n",
      "源代码:\n",
      "def hello_world(abc):\n",
      "    print(\"Hello, world!\")\n",
      "    return abc\n",
      "\n",
      "代码解释:\n",
      "\n",
      "当然可以！以下是按照你提供的格式输出的函数信息：\n",
      "\n",
      "---\n",
      "\n",
      "**函数名称**: hello_world  \n",
      "**源代码**:\n",
      "```python\n",
      "def hello_world(abc):\n",
      "    print(\"Hello, world!\")\n",
      "    return abc\n",
      "```\n",
      "**代码解释**:  \n",
      "该函数名为 `hello_world`，接受一个参数 `abc`（类型不限）。函数内部首先打印字符串 `\"Hello, world!\"`，然后将传入的参数 `abc` 原样返回。此函数通常用于演示基本的函数结构和打印输出功能。\n",
      "\n",
      "--- \n",
      "\n",
      "如果你需要我扩展测试用例、说明调用方式或分析返回值，请随时告诉我！\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import inspect\n",
    "import requests\n",
    "import json\n",
    "\n",
    "# 配置阿里云的 API 密钥和基础 URL\n",
    "api_key = \"sk-4e88cf4db3e14894bafaff606d296610\"\n",
    "api_base = \"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions\"\n",
    "\n",
    "# 定义一个简单的函数作为示例效果\n",
    "def hello_world(abc):\n",
    "    print(\"Hello, world!\")\n",
    "    return abc\n",
    "\n",
    "PROMPT = \"\"\"\\\n",
    "你是一个非常有经验和天赋的程序员，现在给你如下函数名称，你会按照如下格式，输出这段代码的名称、源代码、中文解释。\n",
    "函数名称: {function_name}\n",
    "源代码:\n",
    "{source_code}\n",
    "代码解释:\n",
    "\"\"\"\n",
    "\n",
    "def get_source_code(function_name):\n",
    "    # 获得源代码\n",
    "    return inspect.getsource(function_name)\n",
    "\n",
    "# 自定义的模板 class\n",
    "class CustomPrompt:\n",
    "    def format(self, **kwargs) -> str:\n",
    "        # 获得源代码\n",
    "        source_code = get_source_code(kwargs[\"function_name\"])\n",
    "\n",
    "        # 生成提示词模板\n",
    "        prompt = PROMPT.format(\n",
    "            function_name=kwargs[\"function_name\"].__name__, source_code=source_code\n",
    "        )\n",
    "        return prompt\n",
    "\n",
    "a = CustomPrompt()\n",
    "pm = a.format(function_name=hello_world)\n",
    "\n",
    "print(pm)\n",
    "\n",
    "# 使用阿里云的 API 进行预测\n",
    "headers = {\n",
    "    \"Authorization\": f\"Bearer {api_key}\",\n",
    "    \"Content-Type\": \"application/json\"\n",
    "}\n",
    "\n",
    "data = {\n",
    "    \"model\": \"qwen-plus\",\n",
    "    \"messages\": [\n",
    "        {\"role\": \"user\", \"content\": pm}\n",
    "    ]\n",
    "}\n",
    "\n",
    "response = requests.post(api_base, headers=headers, data=json.dumps(data))\n",
    "\n",
    "if response.status_code == 200:\n",
    "    print(response.json()[\"choices\"][0][\"message\"][\"content\"])\n",
    "else:\n",
    "    print(f\"Error: {response.status_code}\")\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7c36fab3-a536-4b40-b338-cb25117e667c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "rag_learn",
   "language": "python",
   "name": "rag_learn"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
